import { Injectable } from '@angular/core';
import { GlobalsProvider } from '../globals/globals';
import $ from 'jquery';
import { LoginPage } from '../../pages/login/login';
import { AlertController } from 'ionic-angular';

/*
  Generated class for the NetProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class NetProvider {

  constructor(private globals: GlobalsProvider, private alertCtrl: AlertController) {

  }



  public processSuccessResponse = (response, textState, xhr) => {
    
  }

  public processErrorResponse = (xhr, textStatus, e) => {
    const alert = this.alertCtrl.create({
      title: '错误!',
      subTitle: '发生系统级错误!',
      buttons: ['确定']
    });
    alert.present();
  }

  public beforeSend = (me, xhr) => {
    if (me.globals.authToken) {
      xhr.setRequestHeader("X-AUTH-TOKEN", me.globals.authToken);
    }
  }


  postJson(url: string, data, success, error) {
    let me = this;
    $.ajax({
      url: url,
      contentType: "application/json",
      type: "post",
      context: me,
      cache: false,
      beforeSend: (xml) => {
        this.beforeSend(this, xml);
      },
      data: JSON.stringify(data),
      success: (data, textStatus, xhr) => {
        me.processSuccessResponse(data, textStatus, xhr);
        if (success) {
          success(data, textStatus, xhr);
        }
      },
      error: (xhr, status, err) => {
        me.processErrorResponse(xhr, status, err);
        if (error) {
          error(xhr, status, err);
        }
      }
    });
  }


  post(url: string, data, success, error) {
    let me = this;
    $.ajax({
      url: url,
      type: "post",
      beforeSend: (xml) => {
        me.beforeSend(me, xml);
      },
      context: me,
      cache: false,
      data: data,
      success: (data, textStatus, xhr) => {
        me.processSuccessResponse(data, textStatus, xhr);
        if (success) {
          success(data, textStatus, xhr);
        }
      },
      error: (xhr, status, err) => {
        me.processErrorResponse(xhr, status, err);
        if (error) {
          error(xhr, status, err);
        }
      }
    });
  }

  public encodeComplexHttpParams(params: any): any {
    let appendBody = "";
    for (let key in params) {
      console.log(key);
      if (appendBody.length > 0) {
        appendBody = appendBody + "&";
      }
      let value = params[key];
      appendBody += (key + "=" + decodeURIComponent(value));
    }
    return appendBody;
  }

}
